< previous page page_332 next page >

Page 332
0332-01.gif
Figure T5-2:
Passing a numeric variable by reference
In the previous example, the variable myvar is unchanged. But when it is passed by reference, the location (or memory address) of the variable is placed on the stack instead of the value of the variable. When the CalledByRef function refers to x, it still looks on the stack, but instead of using the value it finds there, it uses that value to determine where x is actually located. The value in the stack serves as a pointer to variable x. When the CalledByRef function attempts to read or modify the value of x, it uses the pointer to find the location of the myvar parameter and accesses that location, so changes to x serve to change variable myvar. How does the CalledByRef function know that the stack contains a pointer instead of a value? It knows this because you told it how to use the value on the stack when you declared the function.
How does a DLL or API function know that the stack contains a pointer instead of a value? The same waythe person writing the DLL or API function specified the type of parameter in the source code for the function. But Visual Basic has no automatic way of knowing what it should put on the stack for these functions. It's up to you, in the Declare statement, to tell Visual Basic exactly how to pass the parameter to the function. If you make a mistake, not only will the function call fail, it will probably lead to a memory exception. For example, say you have an API function that expects a Long value to be passed by reference, but you declare it by value. If the variable contains 0, Visual Basic will put 0 on the stack (called by value). The API function will look on the stack for the location of the variable and see that it is at location 0. When the function tries to read or write the variable itself (thinking it's at location 0), a memory exception will result.
Any 32-bit variable that contains the location of another variable instead of the value is called a pointer, and you'll soon see that there are many ways to deal with pointers when making API calls.

 
< previous page page_332 next page >